package com.csmk.springboot_simple.mybatis;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Properties;

@Component
@Intercepts({
        @Signature(type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class, Integer.class})
})
public class UserIdReplacementInterceptor implements Interceptor {

    // 这里可以注入你获取用户ID的逻辑
    private String getCurrentUserId() {
        // 实现获取当前用户ID的逻辑
        // 可以从ThreadLocal、SecurityContext等获取
        return "12345"; // 示例值
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);

        // 获取原始SQL
        String originalSql = (String) metaObject.getValue("delegate.boundSql.sql");

        if (originalSql != null && originalSql.contains("@userId")) {
            // 替换@userId为实际值
            String modifiedSql = originalSql.replace("@userId", getCurrentUserId());

            // 设置修改后的SQL
            metaObject.setValue("delegate.boundSql.sql", modifiedSql);
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以接收配置参数
    }
}